<script setup lang="ts">
import TableView from '@/components/TableView.vue'
import {
  NButton,
  NDataTable,
  NForm,
  NFormItem,
  NPagination,
  useMessage,
  NSelect,
  type DataTableColumns,
  NSpace,
  NModal
} from 'naive-ui'
import { h, ref, reactive, watch, onDeactivated } from 'vue'
import router from '@/router'
import { useRoute } from 'vue-router'
import { sendRequest } from '@/utils/api'
import { useViewerStore } from '../Common/store'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import { RecordType } from '@/router/utils'

const message = useMessage()
const route = useRoute()
const useStore = useViewerStore()

const rowKey: any = (e: any) => e.id || ''
const columns: DataTableColumns = [
  {
    title: '用户',
    key: 'userName',
    width: '5rem',
    align: useStore.isCenter
  },
  {
    title: '部门',
    key: 'deptName',
    width: '10rem',
    align: useStore.isCenter
  },
  {
    title: '信访形式',
    key: 'letterVisitType',
    width: '10rem',
    align: useStore.isCenter
  },
  // {
  //   title: '受理部门',
  //   key: 'acceptDeptName',
  //   width: '10rem',
  //   align: useStore.isCenter
  // },
  {
    title: '办理时限(天)',
    key: 'dealDay',
    width: '10rem',
    align: useStore.isCenter
  },
  {
    title: '提交时间',
    key: 'submitTime',
    width: '10rem',
    align: useStore.isCenter
  },
  {
    title: '审批状态',
    key: 'fromStatus',
    width: '5rem',
    align: useStore.isCenter
  },
  {
    title: '操作',
    key: 'action',
    width: '10rem',
    align: useStore.isCenter,
    fixed: 'right',
    render: (e: any) => [
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          onClick: () => {
            RecordType.setRouteNameTypeFalse('A0516')
            handleDetail(e)
          }
        },
        {
          default: () => '详情'
        }
      ),
      h(
        NButton,
        {
          type: 'info',
          loading: exportLoading.value,
          quaternary: true,
          style: {
            display: e.fromStatusCode == 'A0605' ? 'inline-flex' : 'none'
          },
          onClick: () => handleExport(e)
        },
        {
          default: () => '导出'
        }
      ),
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          style: {
            display: e.fromStatusCode == 'A0603' ? 'inline-flex' : 'none'
          },
          onClick: () => handleBack(e)
        },
        {
          default: () => '撤回'
        }
      ),
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          onClick: () => handleAgainAdd(e)
        },
        {
          default: () => '再次发起'
        }
      )
    ]
  }
]

//筛选条件
const typeVal: any = ref()
const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 0,
  onChange: (page: number) => {
    paginationReactive.page = page
    queryTableData()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
    queryTableData()
  }
})

//信访形式
const partList: any = ref([])
const getRoomType = async () => {
  const [error, res] = await sendRequest({
    module: 'office',
    api: 'roomType',
    override: {
      params: {
        dicCode: 'A15'
      }
    }
  })
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  partList.value = []
  res.data.map((i: any) => {
    partList.value.push({
      label: i.dicName,
      value: i.dicCode
    })
  })
}
getRoomType()

//信访申请
const handleAdd = () => {
  router.push({
    path: '/OA/Petition/PetitionAdd'
  })
}

//再次发起
const handleAgainAdd = (val: any) => {
  router.push({
    path: '/OA/Petition/PetitionEdit',
    query: {
      id: val.id,
      flag: 1
    }
  })
}

//详情
const handleDetail = (val: any) => {
  router.push({
    path: '/OA/Petition/PetitionDetail',
    query: {
      id: val.id
    }
  })
}

//撤回
const modalVisible = ref(false)
const modalId = ref()
const handleBack = async (val: any) => {
  modalId.value = val?.id
  modalVisible.value = true
}

const againBack = async () => {
  const [error, res] = await sendRequest({
    module: 'petition',
    api: 'petitionBack',
    override: {
      params: {
        id: modalId.value
      }
    }
  })
  if (error) return message.error(error.message)
  message.success(res.data)
  modalVisible.value = false
  queryTableData()
}

//表格数据
const tableLoading = ref(false)
const tableData: any = ref([])
const queryTableData = async (resetPage = false) => {
  if (resetPage) paginationReactive.page = 1
  tableLoading.value = true
  const [error, res] = await sendRequest({
    module: 'petition',
    api: 'petitionList',
    override: {
      params: {
        letterVisitTypeCode: typeVal.value,
        page: paginationReactive.page,
        limit: paginationReactive.pageSize
      }
    }
  })
  tableLoading.value = false
  if (error) return message.error(error.message)
  paginationReactive.itemCount = res.data?.totalCount
  const tmp: any = res.data
  tableData.value = tmp?.list
}

//导出
function download(headers: any, data: any, name?: string) {
  const val = headers['content-disposition']?.match(/(?<=filename=)(.*)/)
  let filename = val ? decodeURIComponent(val[0]) : name + '.xlsx'
  if (!filename.includes('xlsx')) {
    filename = filename.replace('xls', 'xlsx')
  }
  const a = document.createElement('a')
  let binaryData = []
  binaryData.push(data)
  a.href = window.URL.createObjectURL(new Blob(binaryData))
  a.download = filename
  a.click()
  window.URL.revokeObjectURL(a.href)
}
const exportLoading = ref(false)
async function handleExport(val: any) {
  exportLoading.value = true
  const [error, data, headers] = await sendRequest({
    module: 'petition',
    api: 'petitionExport',
    override: {
      params: {
        id: val.id
      }
    }
  })
  if (error) return message.error(error.message)
  download(headers, data, '信访审批单')
  exportLoading.value = false
}

const keyUpDown = (e: any) => e.key == 'Enter' && (paginationReactive.page = 1,queryTableData(true))
onDeactivated(() => window.removeEventListener('keyup', keyUpDown, false))

watch(
  () => route.path,
  async () => {
    if (route.path == '/OA/Petition/petitionList') {
      await queryTableData()
      window.addEventListener('keyup', keyUpDown, false)
    }
  },
  { deep: true, immediate: true }
)
</script>

<template>
  <TableView class="table">
    <template #form>
      <NSpace justify="space-between">
        <NForm :show-feedback="false" label-placement="left" inline>
          <NFormItem label="信访形式:">
            <NSelect :options="partList"  v-model:value="typeVal" placeholder="请选择信访形式" clearable
              style="width: 200px" />
          </NFormItem>
          <NFormItem>
            <NButton type="primary" style="width: 78px; margin-right: 40rem" ghost @click="queryTableData(true)">
              查询
            </NButton>
          </NFormItem>
        </NForm>
        <NSpace align="end">
          <NButton type="primary" style="width: 115px" @click="handleAdd">
            信访申请
          </NButton>
        </NSpace>
      </NSpace>
    </template>

    <template #table="props">
      <NDataTable v-bind="props" :bordered="false" :row-key="rowKey" :columns="columns" :data="tableData"
        :loading="tableLoading" />
    </template>

    <template #pagination>
      <NPagination :page-sizes="paginationReactive.pageSizes" :item-count="paginationReactive.itemCount"
        :page="paginationReactive.page" :page-size="paginationReactive.pageSize"
        @update:page="paginationReactive.onChange" @update:page-size="paginationReactive.onUpdatePageSize"
        show-size-picker show-quick-jumper :suffix="() => '页'">
        <template #prefix>
          <span style="font-size: 14px;"> 共{{ paginationReactive.itemCount }}条</span>
        </template>
      </NPagination>
    </template>
  </TableView>

  <NModal :auto-focus="false" v-model:show="modalVisible">
    <VDialogContent @close="modalVisible = false" @submit="againBack" title="撤回提示">
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        您确定要撤回吗?
      </div>
    </VDialogContent>
  </NModal>
</template>

<style scoped lang="scss">
.table {
  height: 100%;
  padding: 29px 30px 42px;
}
</style>
